//
//  BXDtlViewController.swift
//  HuaYun
//
//  Created by Mac on 2019/3/25.
//  Copyright © 2019 xyxorigation. All rights reserved.
//

import UIKit

class BXDtlViewController: PurchaseTableViewController {
    
    var headsource: [Dictionary<String,String?>] = []
    
    var tickets: [JSON] = []
    
    var convertedTickets: [[Dictionary<String,String?>]] {
        get{
            return self.tickets.map({ (item) -> [Dictionary<String,String?>] in
                var projs: [Dictionary<String,String?>] = []
                projs.append(["发票类型:": item["invoiceTypeName"].string])
                projs.append(["税率:": item["taxrateName"].string])
                let tax = item["taxMoney"].double ?? 0
                projs.append(["报销含税金额(元):": String.init(format: "%.2f", tax / 100.0)])
                let nottax = item["notTaxMoney"].double ?? 0
                projs.append(["报销不含税金额(元):": String.init(format: "%.2f", nottax / 100.0)])
                return projs
            })
        }
    }
    
    var bottomsource: [Dictionary<String,String?>] = []
    
    var projects: [JSON] = []
    
    var convertedProjects: [[Dictionary<String,String?>]] {
        get{
            return self.projects.map({ (item) -> [Dictionary<String,String?>] in
                var tmp: [Dictionary<String,String?>] = []
                tmp.append(["综合计划编号:": item["comprehensivePlanNumber"].string])
                tmp.append(["综合计划名称:": item["comprehensivePlanName"].string])
                tmp.append(["项目编号:": item["projNumber"].string])
                tmp.append(["项目名称:": item["projName"].string])
                let projCost = (item["projCost"].double ?? 0.0) / 100
                tmp.append(["项目分摊金额(元):": String.init(format: "%.2f", projCost)])
                return tmp
            })
        }
    }
    
    override var source: Array<Dictionary<String, String?>>{
        get{
            var projs: Array<Dictionary<String,String?>> = []
            
            for item in self.projects {
                projs.append(["发票类型:": item["invoiceTypeName"].string])
                projs.append(["税率:": item["taxrateName"].string])
                let tax = item["taxMoney"].double ?? 0
                projs.append(["报销含税金额(元):": String.init(format: "%.2f", tax / 100.0)])
                let nottax = item["notTaxMoney"].double ?? 0
                projs.append(["报销不含税金额(元):": String.init(format: "%.2f", nottax / 100.0)])
            }
            
            var ticks: Array<Dictionary<String,String?>> = []
            for item in self.tickets {
                ticks.append(["发票类型:": item["invoiceTypeName"].string])
                ticks.append(["税率:": item["taxrateName"].string])
                let tax = item["taxMoney"].double ?? 0
                ticks.append(["报销含税金额(元):": String.init(format: "%.2f", tax / 100.0)])
                let nottax = item["notTaxMoney"].double ?? 0
                ticks.append(["报销不含税金额(元):": String.init(format: "%.2f", nottax / 100.0)])
            }
            return headsource + projs + ticks + bottomsource
        }
        set{
            
        }
    }
    override func viewDidLoad() {
        super.viewDidLoad()
    }

    override func numberOfSections(in tableView: UITableView) -> Int {
        
        return self.convertedTickets.count + 3 + self.convertedProjects.count
        
    }
    
    override func tableView(_ tableView: UITableView, numberOfRowsInSection section: Int) -> Int {
        if section == 0 {
            return self.headsource.count
        } else if section <= self.convertedTickets.count {
            return self.convertedTickets[section - 1].count
        } else if section <= self.convertedProjects.count + self.convertedTickets.count {
            return self.convertedProjects[section - self.convertedTickets.count - 1].count
        } else if section == self.tickets.count + self.projects.count + 1 {
            return self.bottomsource.count
        } else {
            return self.documents.count
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForRowAt indexPath: IndexPath) -> CGFloat {
        if indexPath.section == 0 {
            if let content = self.headsource[indexPath.row].first?.value {
                
                if content.count > 0{
                    
                    let size = content.size(with: UIFont.systemFont(ofSize: 15), maxSize: CGSize.init(width: tableView.width - 32, height: 1000000))
                    
                    return 55 + size.height
                    
                } else {
                    
                    return 65
                    
                }
            } else {
                return 65
            }
        } else if indexPath.section <= self.tickets.count {
            let target = self.convertedTickets[indexPath.section - 1][indexPath.row]
            if let content = target.first?.value {
                if content.count > 0{
                    let size = content.size(with: UIFont.systemFont(ofSize: 15), maxSize: CGSize.init(width: tableView.width - 32, height: 1000000))
                    return 55 + size.height
                } else {
                    return 65
                }
            } else {
                return 65
            }
        } else if indexPath.section <= self.convertedProjects.count + self.convertedTickets.count {
            if let content = self.convertedProjects[indexPath.section - self.convertedTickets.count - 1][indexPath.row].first?.value {
                if content.count > 0{
                    let size = content.size(with: UIFont.systemFont(ofSize: 15), maxSize: CGSize.init(width: tableView.width - 32, height: 1000000))
                    return 55 + size.height
                } else {
                    return 65
                }
            } else {
                return 65
            }
        } else if indexPath.section == self.convertedProjects.count + self.convertedTickets.count + 1 {
            if let content = self.bottomsource[indexPath.row].first?.value {
                if content.count > 0{
                    
                    let size = content.size(with: UIFont.systemFont(ofSize: 15), maxSize: CGSize.init(width: tableView.width - 32, height: 1000000))
                    
                    return 55 + size.height
                    
                } else {
                    
                    return 65
                    
                }
            } else {
                return 65
            }
            
        } else if indexPath.section == self.tickets.count + self.projects.count + 2 {
            let name = self.documents[indexPath.row].contents?["name"]?.rawString() ?? ""
            if let cell = tableView.cellForRow(at: indexPath) {
                let size = name.size(with: cell.textLabel!.font, maxSize: CGSize.init(width: self.view.width - 48, height: 10000))
                return size.height > 55 ? size.height  : 55
            } else {
                return 55
            }
        } else {
            return 55
        }
    }
    
    override func tableView(_ tableView: UITableView, cellForRowAt indexPath: IndexPath) -> UITableViewCell {
        if indexPath.section < self.tickets.count + self.projects.count + 2 {
            return tableView.dequeueReusableCell(withIdentifier: "ApprovalDetailCell")!
        } else {
            var cell = tableView.dequeueReusableCell(withIdentifier: "Attachment")
            if cell == nil {
                cell = UITableViewCell.init(style: .default, reuseIdentifier: "Attachment")
                cell?.textLabel?.numberOfLines = 0
            }
            
            cell?.imageView?.image = UIImage(named: "icon_attachment")
            
            cell?.textLabel?.font = UIFont.systemFont(ofSize: 15)
            
            cell?.textLabel?.textColor = UIColor.hex("458AE0")
            
            if indexPath.row < documents.count {
                cell?.textLabel?.text = documents[indexPath.row].contents?["name"]?.rawString()
            }
            
            return cell!
        }
    }
    
    override func tableView(_ tableView: UITableView, willDisplay cell: UITableViewCell, forRowAt indexPath: IndexPath) {
        if indexPath.section == 0 {
            if let cel = cell as? ApprovalDetailCell {
                if indexPath.row < source.count {
                    cel.title = source[indexPath.row].keys.first
                    
                    if let content = source[indexPath.row].first?.value {
                        
                        cel.content = content
                        
                    } else {
                        cel.content = ""
                    }
                }
            }
        } else if indexPath.section <= self.convertedTickets.count {
            let target = self.convertedTickets[indexPath.section - 1][indexPath.row]
            if let cel = cell as? ApprovalDetailCell {
                if indexPath.row < 4 {
                    cel.title = target.keys.first
                    
                    if let content = target.first?.value {
                        
                        cel.content = content
                        
                    } else {
                        cel.content = ""
                    }
                }
            }
        } else if indexPath.section <= self.convertedProjects.count + self.convertedTickets.count {
            if let cel = cell as? ApprovalDetailCell {
                cel.title = self.convertedProjects[indexPath.section - self.convertedTickets.count - 1][indexPath.row].keys.first
                if let content = self.convertedProjects[indexPath.section - self.convertedTickets.count - 1][indexPath.row].first?.value {
                    
                    cel.content = content
                    
                } else {
                    cel.content = ""
                }
            }
        } else if indexPath.section == self.tickets.count + self.projects.count + 1 {
            if let cel = cell as? ApprovalDetailCell {
                if indexPath.row < self.bottomsource.count {
                    cel.title = self.bottomsource[indexPath.row].keys.first
                    
                    if let content = self.bottomsource[indexPath.row].first?.value {
                        
                        cel.content = content
                        
                    } else {
                        cel.content = ""
                    }
                }
            }
        }
    }
    
    override func tableView(_ tableView: UITableView, heightForHeaderInSection section: Int) -> CGFloat {
        if section == 0 {
            return 10
        } else if section <= self.projects.count + self.tickets.count {
            return 40
        } else if section == self.tickets.count + self.projects.count + 1 {
            return 10
        } else if section == self.tickets.count + self.projects.count + 2 {
            return 40
        } else {
            return 0.0
        }
    }
    
    override func tableView(_ tableView: UITableView, viewForHeaderInSection section: Int) -> UIView? {
        if section == 0 {
            return nil
        }
        
        if section <= self.tickets.count {
            let view = UIView()
            view.backgroundColor = UIColor.hex("eeeeee")
            let label = UILabel.init()
            label.text = "发票明细" + "(" + String(section) + ")"
            label.textColor = UIColor.hex("666666")
            label.font = UIFont.systemFont(ofSize: 14)
            label.width = label.text!.size(with: label.font).width
            label.height = label.text!.size(with: label.font).height
            label.left = 15
            label.top = 22 - label.height / 2
            view.addSubview(label)
            return view
        }
        if section <= self.projects.count + self.tickets.count {
            let view = UIView()
            view.backgroundColor = UIColor.hex("eeeeee")
            let label = UILabel.init()
            let idx = section - self.tickets.count
            label.text = "项目明细" + "(" + String(idx) + ")"
            label.textColor = UIColor.hex("666666")
            label.font = UIFont.systemFont(ofSize: 14)
            label.width = label.text!.size(with: label.font).width
            label.height = label.text!.size(with: label.font).height
            label.left = 15
            label.top = 22 - label.height / 2
            view.addSubview(label)
            return view
        }
        if section == self.tickets.count + self.projects.count + 2 {
            let footer = UIView()
            
            footer.backgroundColor = UIColor.dftBack
            
            footer.backgroundColor = UIColor.white
            
            let titleLbl = UILabel()
            
            titleLbl.textColor = UIColor.textColor
            
            titleLbl.font = UIFont.systemFont(ofSize: 15)
            
            titleLbl.text = "附件:"
            
            titleLbl.frame = CGRect(origin: CGPoint(x: 15.0, y: 15.0), size: CGSize(width: titleLbl.contentSize.width, height: titleLbl.contentSize.height))
            
            footer.addSubview(titleLbl)
            
            return footer
        }
        return nil
    }
    
    override func tableView(_ tableView: UITableView, didSelectRowAt indexPath: IndexPath) {
        tableView.deselectRow(at: indexPath, animated: true)
        switch indexPath.section {
        case self.tickets.count + self.projects.count + 2:
            let load = loadExcelViewController()
            if let id = documents[indexPath.row].contents?["id"]?.rawString() {
                let p = Server + FilePath.Finacial.rawValue + "?id=" + id
                NetManager.download(path: p, prog: { (progress) in
                    SVProgressHUD.showProgress(Float(progress))
                }) { (file) in
                    
                    SVProgressHUD.dismiss()
                    
                    let previewURL = PreviewURL(url: file, name: self.documents[indexPath.row].contents?["name"]?.rawString())
                    
                    load.path = previewURL
                    
                    let root = UIApplication.shared.keyWindow?.rootViewController
                    root?.present(load, animated: true, completion: nil)
                    
                }
            }
            return
        default:
            return
        }
    }

}
